import React, { Component } from 'react';
import { Form, Input, Button, DatePicker, Row, Col, Cascader, Switch, message, Select } from 'antd';
import moment from 'moment';

import 'braft-editor/dist/index.css';
import 'braft-extensions/dist/table.css'
import Table from 'braft-extensions/dist/table'

import BraftEditor from 'braft-editor';

import ImageBox from '@/components/ImageBox';

import { InfoTypeList, uploadFile } from "@/services/info";
const arrayToTree = require('array-to-tree');

import styles from './index.less';
import path from "path"

import {
  CloudOutlined,
  EditOutlined,
} from '@ant-design/icons';

const options = {
  defaultColumns: 3, // 默认列数
  defaultRows: 3, // 默认行数
  withDropdown: false, // 插入表格前是否弹出下拉菜单
  columnResizable: false, // 是否允许拖动调整列宽，默认false
  exportAttrString: '', // 指定输出HTML时附加到table标签上的属性字符串
}
BraftEditor.use(Table(options))



class InfoForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      arr: [],
      block: "",
      options: [],
      disabled: true,
      infoTypeName: "",
    };
    InfoTypeList().then(({ result, success }) => {
      if (success) {
        const tempArr = result.arr.map(item => ({ ...item, value: item.id.toString(), label: item.infoTypeName, fid: item.fid.toString() }))
        const options = arrayToTree(tempArr, { rootID: "0", parentProperty: "fid", customID: "value", childrenProperty: "children" })
        //获取当前选择的栏目名字
        if (this.props.infoType !== undefined) {
          this.setState({ options, infoTypeName: tempArr.find(item => item.id == this.props.infoType[1]).displayName })
        }
        else {
          this.setState({ options, })
        }
      }
    })
  }
  componentDidMount() {
    const { title, titleSub, infoType, isEnable, body, bodySub, pubTime, cover, viewNum, orderNum, remark } = this.props;

    this.myform.setFieldsValue({
      title: title === undefined ? "" : title,
      titleSub: titleSub === undefined ? "" : titleSub,
      infoType: infoType === undefined ? [] : infoType,
      isEnable: isEnable === undefined ? false : isEnable,
      body: body === undefined ? BraftEditor.createEditorState('') : BraftEditor.createEditorState(body),
      bodySub: bodySub === undefined ? "" : bodySub,
      pubTime: pubTime === undefined ? moment() : moment(pubTime),
      cover: cover === undefined ? "" : cover,
      viewNum: viewNum === undefined ? "0" : viewNum.toString(),
      orderNum: orderNum === undefined ? "0" : orderNum.toString(),
      remark: remark === undefined ? "" : remark,
    });
    //将按钮的submit递交给父组件
    if (this.props.sendSubmit) {
      this.props.sendSubmit(this.myform.submit)
    }
  }

  // async uploadFn(param) {
  //   const formData = new FormData();
  //   formData.append('file', param.file);
  //   //控制进度条--------
  //   let progress = 0;
  //   let s = setInterval(() => {
  //     if (progress == 98) {
  //       clearInterval(s);
  //       return;
  //     }
  //     progress = progress + 1;
  //     param.progress(progress);
  //   }, 50)
  //   //控制进度条--------

  //   const res = await uploadFile(formData);

  //   //完成了
  //   clearInterval(s);
  //   param.progress(100);

  //   if (res.success) {
  //     param.success({
  //       url: res.result[0],
  //     })
  //   }
  //   else {
  //     param.error({
  //       msg: '上传出错.'
  //     })
  //   }
  // }

  uploadFn(param) {

    const serverURL = '/api/info/uploadFile'
    const xhr = new XMLHttpRequest
    const fd = new FormData()

    const successFn = (response) => {
      // 假设服务端直接返回文件上传后的地址
      // 上传成功后调用param.success并传入上传后的文件地址
      if (xhr.status < 400) {
        const res = JSON.parse(xhr.responseText);
        if (!res.success) {
          message.error(JSON.stringify(res.result));
          param.error({
            msg: '上传出错'
          })
        }
        else {
          param.success({
            url: res.result[0],
          })
        }

      }
      else {
        param.error({
          msg: '上传出错'
        })
      }

    }

    const progressFn = (event) => {
      // 上传进度发生变化时调用param.progress
      param.progress(event.loaded / event.total * 100)
    }

    const errorFn = (response) => {
      // 上传发生错误时调用param.error
      param.error({
        msg: '上传出错'
      })
    }

    xhr.upload.addEventListener("progress", progressFn, false)
    xhr.addEventListener("load", successFn, false)
    xhr.addEventListener("error", errorFn, false)
    xhr.addEventListener("abort", errorFn, false)

    fd.append('file', param.file)
    xhr.open('POST', serverURL, true)
    xhr.setRequestHeader("auth", localStorage.getItem("authInfo"))
    xhr.send(fd)
  }
  createRemark() {
    if (this.state.infoTypeName == "文化日历") {

      return (<Form.Item
        label="类型"
        name={['remark']}
        rules={[{ required: true }]}
      >
        <Select options={[
          { label: "通知公告", value: "通知公告" },
          { label: "讲座活动", value: "讲座活动" },
          { label: "大事记", value: "大事记" },
          { label: "新纪录", value: "新纪录" },
        ]} />
      </Form.Item>);
    }
    if (this.state.infoTypeName == "师资队伍") {
      return (<Form.Item
        label="类型"
        name={['remark']}
        rules={[{ required: true }]}
      >
        <Select options={[
          {
            value: "教学名师|湖北省职教名师、武汉市教育界名师",
            label: "教学名师>湖北省职教名师、武汉市教育界名师",
          },
          {
            value: "教学名师|武汉市教育界名师",
            label: "教学名师>武汉市教育界名师",
          },
          {
            value: "教学名师|湖北省金牌教师",
            label: "教学名师>湖北省金牌教师",
          },
          {
            value: "教学名师|武汉技师学院首届教学名师",
            label: "教学名师>武汉技师学院首届教学名师",
          },
          {
            value: "技能大师|国家级技能大师",
            label: "技能大师>国家级技能大师",
          },
          {
            value: "技能大师|武汉市技能大师",
            label: "技能大师>武汉市技能大师",
          },
          {
            value: "技能大师|全国技术能手",
            label: "技能大师>武汉市技能大师",
          },
          {
            value: "技能大师|湖北省首席技师",
            label: "技能大师>武汉市技能大师",
          },
          {
            value: "技能大师|武汉市技术能手",
            label: "技能大师|武汉市技术能手",
          },
          {
            value: "技能大师|武汉技师学院首届岗位能手",
            label: "技能大师>武汉技师学院首届岗位能手",
          },
          {
            value: "学科带头人",
            label: "学科带头人",
          },
          {
            value: "优秀青年教师",
            label: "优秀青年教师",
          },
        ]} />
      </Form.Item>)
    }
    return (
      null
      // <Form.Item
      //   label="备注"
      //   name={['remark']}
      // >
      //   <Input disabled={this.state.disabled} addonAfter={<EditOutlined onClick={() => this.setState({ disabled: !this.state.disabled })} />} />
      // </Form.Item>
    )
  }
  render() {

    return (
      <div className={styles.block}>
        <Form
          layout="vertical"
          ref={(_) => (this.myform = _)}
          scrollToFirstError={true}
          onFinish={(fieldsValue) => {
            const { onFinish } = this.props;
            const returnObj = {
              ...fieldsValue,
              body: fieldsValue["body"].toHTML(),
              pubTime: fieldsValue["pubTime"].format('YYYY-MM-DD HH:mm'),
            };
            if (onFinish) {
              onFinish(returnObj)
            }
          }}
        >
          <Row gutter={[24, 0]}>
            <Col xs={24} sm={24} md={24} lg={12} >
              <Form.Item
                label="主标题"
                name={['title']}
                rules={[{ required: true }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col xs={24} sm={24} md={24} lg={12} >
              <Form.Item
                label="副标题"
                name={['titleSub']}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[24, 0]}>
            <Col xs={24} sm={24} md={24} lg={12} >
              <Form.Item
                label="栏目"
                name={['infoType']}
                rules={[{ type: "array", required: true }]}
              >
                <Cascader onChange={(_, s) => {
                  if (s.length != 2) {
                    return;
                  }
                  this.setState({
                    infoTypeName: s[1].displayName
                  })
                }} options={this.state.options} placeholder="选择要发布的到哪个栏目下" />
              </Form.Item>
            </Col>
            <Col xs={24} sm={24} md={24} lg={12} >
              <Form.Item
                label="是否可用"
                name={['isEnable']}
                valuePropName="checked"
              >
                <Switch checkedChildren={"启用"} unCheckedChildren={"禁用"} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[24, 0]}>
            <Col xs={24} sm={24} md={24} lg={24} >
              {this.createRemark()}
            </Col>
          </Row>
          <Form.Item
            label={<span>
              <Button
                onClick={() => {
                  const { blocks, entityMap } = this.myform.getFieldValue("body").toRAW(true);
                  const newBlock = blocks.map(item => {
                    if (item.type == "unstyled" && item.text.trim() != "") {
                      return {
                        ...item,
                        text: item.text.trimLeft(),
                        data: {
                          ...item.data,
                          textIndent: 1,
                        },
                      }
                    }
                    if (item.type == "atomic") {
                      return {
                        ...item,
                        data: {
                          ...item.data,
                          nodeAttributes: { class: "media-wrap image-wrap" },
                        },
                      }
                    }
                    return {
                      ...item,
                    }
                  })
                  const entArr = Object.keys(entityMap).map(item => entityMap[item]).map(item => ({
                    ...item,
                    data: {
                      url: item.data.url,
                      width: "100%",
                    }
                  }));
                  let newEntityMap = {};
                  entArr.forEach((item, index) => {
                    newEntityMap[index] = item;
                  })
                  this.myform.setFieldsValue({
                    body: BraftEditor.createEditorState({
                      blocks: newBlock,
                      entityMap: newEntityMap,
                    })
                  });
                  message.success("排版完成");
                }}
                type="primary" size="small" style={{ marginLeft: "1em" }}><CloudOutlined />智能排版</Button>
            </span>}
            name={['body']}
            validateTrigger={['onBlur']}
            rules={[
              {
                required: true,
                validator: (_, edit) => {
                  if (edit.isEmpty()) {
                    return Promise.reject('请输入正文');
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <BraftEditor
              id="editor-1"

              ref={(_) => (this.myEdit = _)}
              className={styles.BraftEditor}
              contentClassName={styles.BraftEditorContent}
              onChange={(editorState) => {
                const { blocks, entityMap } = editorState.toRAW(true);
                let arr = [];
                for (let key in entityMap) {
                  const myPath = entityMap[key]["data"]["url"];
                  const ext = path.extname(myPath).toLowerCase();
                  if (ext == ".jpg" || ext == ".jpeg" || ext == ".png") {
                    arr.push(entityMap[key]["data"]["url"])
                  }
                }
                const block = blocks[0]["text"];
                this.setState({
                  arr,
                  block,
                })
              }}
              // controls={controls}
              media={{
                uploadFn: this.uploadFn,
                validateFn(file) {
                  return new Promise((resolve, reject) => {
                    const isType = file.type === 'image/jpeg' || file.type === 'image/png'|| file.type === 'video/mp4';
                    if (!isType) {
                      message.error('仅仅支持 JPG/PNG/MP4 文件!');
                      reject(false)
                      return;
                    }
                    if(file.type === 'video/mp4'){
                      const maxSize = 200;
                      const isLt2M = file.size / 1024 / 1024 < maxSize;
                      if (!isLt2M) {
                        message.error(`视频文件必须小于 ${maxSize}MB!`)
                        reject(false)
                        return;
                      }
                    }else{
                      const maxSize = 3;
                      const isLt2M = file.size / 1024 / 1024 < maxSize;
                      if (!isLt2M) {
                        message.error(`图片文件必须小于 ${maxSize}MB!`)
                        reject(false)
                        return;
                      }
                    }
         
                    resolve(true);
                  })

                }
              }}
            />
          </Form.Item>

          <Row gutter={[24, 0]}>
            <Col xs={24} sm={24} md={24} lg={12} >
              <Form.Item
                label={<span>正文摘要<Button
                  disabled={this.state.block == ""}
                  onClick={() => {
                    const block = this.state.block.trim();
                    const bodySub = block.length > 100 ? `${block.substr(0, 100)}` : block;
                    this.myform.setFieldsValue({
                      bodySub,
                    })
                  }}
                  type="primary" size="small" style={{ marginLeft: "1em" }}><CloudOutlined />从正文中截取第一段</Button></span>}
                name={['bodySub']}
              // rules={[{ required: true, message: "请输入正文摘要" }]}
              >
                <Input.TextArea rows={4} maxLength={100} />
              </Form.Item>
            </Col>
            <Col xs={24} sm={24} md={24} lg={12} >
              <Form.Item label="封面图片" name="cover">
                <ImageBox arr={this.state.arr} action="/api/info/uploadfImg" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[24, 0]}>
            <Col xs={24} sm={24} md={24} lg={8} >
              <Form.Item
                label="发布时间"
                name={['pubTime']}
                rules={[{ required: true }]}
              >
                <DatePicker showTime={true} style={{ width: "100%" }} format="YYYY-MM-DD HH:mm" />
              </Form.Item>
            </Col>
            <Col xs={24} sm={24} md={24} lg={8} >
              <Form.Item
                label="热度数（数值越大越靠前）"
                rules={[{ required: true, message: "请输入热度数" }]}
                name={['viewNum']}
              >
                <Input type="number" allowClear />
              </Form.Item>
            </Col>
            <Col xs={24} sm={24} md={24} lg={8} >
              <Form.Item
                label="显示顺序（数值越大越靠前）"
                rules={[{ required: true, message: "请输入显示顺序" }]}
                name={['orderNum']}
              >
                <Input type="number" allowClear />
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <br />
      </div>
    );
  }
}
export default InfoForm;

